package com.tfjybj.itoo.teach.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.dmsdbj.itoo.tool.uuid.BaseUuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.SchoolCalendarEntity;
import com.tfjybj.itoo.teach.model.SchoolCalendarModel;
import com.tfjybj.itoo.teach.provider.dao.SchoolCalendarDao;
import com.tfjybj.itoo.teach.provider.service.SchoolCalendarService;
import com.tfjybj.itoo.teach.template.SchoolCalendarImportTemplate;
import com.tfjybj.itoo.teach.template.SchoolCalendarTemplate;
import lombok.extern.slf4j.Slf4j;
import org.jplus.hyberbin.excel.utils.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.tfjybj.itoo.teach.provider.until.DemoConstants.*;

/**
 * SchoolCalendarService接口实现类
 * ${base}表
 *
 * @author 田成荣
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Service("schoolCalendarService")
@Slf4j
public class SchoolCalendarServiceImpl extends BaseServicePlusImpl<SchoolCalendarDao, SchoolCalendarEntity> implements SchoolCalendarService {
	
	//region 模板生成
    @Resource
    private SchoolCalendarDao schoolCalendarDao;

    @Resource
    private RedisTemplate<String, SchoolCalendarTemplate> redisTemplate;


	 @Override
    public PageInfo<SchoolCalendarEntity> queryByLikeEventId(String eventId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
         Map<String,String> eventIdMap = new HashMap<>();
         eventIdMap.put("0","考试周");
         eventIdMap.put("2","选课周");
         eventIdMap.put("3","评教周");
         eventIdMap.put("4","体测周");
         eventIdMap.put("5","节假日");
         eventIdMap.put("6","军训周");
         eventIdMap.put("7","体检周");
         eventIdMap.put("8","新生报到周");
         eventIdMap.put("9","运动会");
         List<SchoolCalendarEntity> schoolCalendarEntities = schoolCalendarDao.queryLikeEventId(eventId);
         for(SchoolCalendarEntity schoolCalendarEntity:schoolCalendarEntities){
             schoolCalendarEntity.setEventId(eventIdMap.get(schoolCalendarEntity.getEventId()));
         }
        return new PageInfo<>(schoolCalendarEntities);
    }
	//endregion

    /* **********************************以下为非模板生成的内容********************************* */


    /**
     * 下载校历信息模板
     * @param response http回应
     * @return
     * @author 刘雅娟
     * @since 2018年11月16日14:41:38
     */
    @Override
    public boolean downTemplate(HttpServletResponse response) {
        Map<Serializable, Serializable> map = new HashMap<>(16);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        List<SchoolCalendarTemplate> templateList = new ArrayList<>();
        SchoolCalendarTemplate schoolCalendarTemplate = new SchoolCalendarTemplate();
        schoolCalendarTemplate.setTermId("2018201901");
        schoolCalendarTemplate.setRoleId("王贵香");
        schoolCalendarTemplate.setEventId("评教周");
        schoolCalendarTemplate.setSchoolYear("2018");
        schoolCalendarTemplate.setStartTime("2018/06/20");
        schoolCalendarTemplate.setEndTime("2018/10/20");
        templateList.add(schoolCalendarTemplate);
        //excel设置
        map.put(SHEET_NAME,"校历信息");
        map.put(COLUMNS, new String[]{"termId", "roleId", "eventId","schoolYear", "startTime", "endTime"});
        map.put(TITLE, "校历信息模板：开始结束时间格式需为日期格式");
        map.put(NAME, "校历信息模板");
        map.put(DATA_LIST, (Serializable) templateList);

        try {
            ExcelUtil.exportExcel(map, response);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**批量导入校历信息
     *
     * @param multipartFile 文件
     * @param request       请求
     * @param response      回应
     * @return  boolean
     * @author 刘雅娟
     * @since 2018年11月25日16:30:50
     */
    @Override
    public ItooResult importTemplate(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("UTF-8");

        try {
            //校验文件是否存在
            String fileName = multipartFile.getOriginalFilename();
            if (fileName == null) {
                log.error("导入失败,fileName is null!");
                return ItooResult.build(ItooResult.FAIL, "传入的文件为空!");
            }

            //定义map方便后续数据存取
            Map<String, SchoolCalendarEntity> schoolCalendarEntityMap = new HashMap<>(16);
            //Excel解析成list
            Map<Serializable, Serializable> map = new HashMap<>(4);
            map.put(SHEET_NAME, "校历信息");
            map.put(CLASS, SchoolCalendarImportTemplate.class);
            List<SchoolCalendarImportTemplate> schoolCalendarImportTemplateList = ExcelUtil.importExcel(Objects.requireNonNull(fileName), map, request, response);
            if (schoolCalendarImportTemplateList.size() == 0) {
                return ItooResult.build(ItooResult.FAIL, "请检查导入的数据");
            }
            //定义导入错误数据集合并存redis中形式<String,FooTemplate>
            List<SchoolCalendarImportTemplate> errorSchoolList = new ArrayList<>();
            String errorSchoolId = IdWorker.getIdStr();
            Long size = redisTemplate.opsForZSet().size(errorSchoolId);
            size = size == null ? 0L : size;

            //循环处理数据,excelSchool为list的每一条
            for(SchoolCalendarImportTemplate excelSchool : schoolCalendarImportTemplateList){
                if(!this.verify(excelSchool)){
                    SchoolCalendarImportTemplate schoolCalendarImportTemplate = new SchoolCalendarImportTemplate();
                    //复制Excel信息到template
                    BeanUtils.copyProperties(excelSchool, schoolCalendarImportTemplate);
                    errorSchoolList.add(schoolCalendarImportTemplate);
                    continue;
                }
                excelSchool = this.changValue(excelSchool);

                //将导入内容放到entity中对应的属性中去
                SchoolCalendarEntity schoolCalendarEntity = new SchoolCalendarEntity();
                //每一条数据复制到实体中
                BeanUtils.copyProperties(excelSchool,schoolCalendarEntity);

                //校历id
                schoolCalendarEntity.setId(BaseUuidUtils.base58Uuid());
                //未删除
                schoolCalendarEntity.setIsDelete(0);
                //保存到数据库
                  this.save(schoolCalendarEntity);
            }
            //不符合条件的信息返回
            if (errorSchoolList.size() > 0) {
                return ItooResult.build("0001","部分导入失败",errorSchoolId);
            }

        }catch (Exception e) {
            return ItooResult.build(ItooResult.FAIL, "导入校历信息异常",e);
        }
        return ItooResult.build(ItooResult.SUCCESS, "导入校历信息成功");
    }


    /**
     * 批量导入前验证数据是否符合要求
     *
     * @param  schoolCalendarImportTemplate
     * @return true:符合导入要求，false：不符合
     * @author 刘雅娟
     * @since 2.0.0 2018-10-19 16:43:03
     */
    private boolean verify(SchoolCalendarImportTemplate schoolCalendarImportTemplate) {
        //判断非空字段是否有值.
        if (StringUtils.isEmpty(schoolCalendarImportTemplate.getEventId())) {
            schoolCalendarImportTemplate.setFailReason("eventId未填写");
            log.warn("导入失败,userCode未填写,excelFooEntity-{}", schoolCalendarImportTemplate);
            return false;
        }
        if (StringUtils.isEmpty(schoolCalendarImportTemplate.getRoleId())) {
            schoolCalendarImportTemplate.setFailReason("roleId未填写");
            log.warn("导入失败,userName未填写,excelFooEntity-{}", schoolCalendarImportTemplate);
            return false;
        }
        String termId = schoolCalendarImportTemplate.getTermId();
        String eventId = schoolCalendarImportTemplate.getEventId();
         schoolCalendarDao.findCalendarEvent(termId,eventId);
        //判断用户名是否重复
        if( schoolCalendarDao.findCalendarEvent(termId,eventId)!=null){
            schoolCalendarImportTemplate.setFailReason("该事件已经存在,请重新导入!");
            log.warn("导入失败,该校历事件已经存在",schoolCalendarImportTemplate);
            return false;
        }
        return true;
    }

    /**
     * 查询所有校历信息
     * @return list
     * @author 刘雅娟
     * @since 2018年11月25日16:31:50
     */
    @Override
    public PageInfo<SchoolCalendarEntity> findSchoolCalender(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        Map<String,String> eventIdMap = new HashMap<>();
         eventIdMap.put("0","考试周");
         eventIdMap.put("2","选课周");
         eventIdMap.put("3","评教周");
         eventIdMap.put("4","体测周");
         eventIdMap.put("5","节假日");
         eventIdMap.put("6","军训周");
         eventIdMap.put("7","体检周");
         eventIdMap.put("8","新生报到周");
         eventIdMap.put("9","运动会");
        List<SchoolCalendarEntity>  schoolCalendarEntities = schoolCalendarDao.findSchoolCalender();
        for(SchoolCalendarEntity schoolCalendarEntity:schoolCalendarEntities){
            schoolCalendarEntity.setEventId(eventIdMap.get(schoolCalendarEntity.getEventId()));
        }
        return new PageInfo<>(schoolCalendarEntities);
    }


    /**
     * 根据年份查询本年的校历信息
     * @param schoolYear
     * @return list
     * @author 刘雅娟
     * @since 2018年11月17日20:06:17
     */
    @Override
    public List<SchoolCalendarEntity> findByYear(String schoolYear) {
        List<SchoolCalendarEntity> schoolCalendarEntity= schoolCalendarDao.findByYear(schoolYear);
        return schoolCalendarEntity;
    }

    /**
     * 获取一周内校历事件
     * @param currentdate
     * @param weekdate
     * @return
     */
    @Override
    public List<SchoolCalendarEntity> findCalenderByDate(String currentdate, String weekdate) {
        List<SchoolCalendarEntity> schoolCalendarEntity= schoolCalendarDao.findCalenderByDate(currentdate,weekdate);
        return schoolCalendarEntity;
    }

    /**
     * event id 字转数字
     * @param schoolCalendarImportTemplate
     * @return SchoolCalendarTemplate
     * @since 2018年11月27日21:29:10
     */
    private SchoolCalendarImportTemplate changValue(SchoolCalendarImportTemplate schoolCalendarImportTemplate){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,String> eventIdMap = new HashMap<>();
        eventIdMap.put("考试周","0");
        eventIdMap.put("教学周","1");
        eventIdMap.put("选课周","2");
        eventIdMap.put("评教周","3");
        eventIdMap.put("体测周","4");
        eventIdMap.put("节假日","5");
        eventIdMap.put("军训周","6");
        eventIdMap.put("体检周","7");
        eventIdMap.put("新生报到周","8");
        eventIdMap.put("运动会","9");
        schoolCalendarImportTemplate.setEventId(eventIdMap.get(schoolCalendarImportTemplate.getEventId()));
        //Excelstring类型转换date类型存入数据库
        try {
            String startTime = schoolCalendarImportTemplate.getStartTimeString();
            schoolCalendarImportTemplate.setStartTime(simpleDateFormat.parse(startTime));
            String endTime = schoolCalendarImportTemplate.getEndTimeString();
            schoolCalendarImportTemplate.setEndTime(simpleDateFormat.parse(endTime));
        }catch (ParseException e){
            e.printStackTrace();
        }
        return schoolCalendarImportTemplate;

    }

    /**
     * 获取一周内校历事件
     * @param chooseClass
     *@since 2018年11月25日20:09:23
     * @return list
     * @author 刘雅娟
     */
    @Override
    public List<SchoolCalendarEntity>  findCalenderChooseClass(String chooseClass) {
        List<SchoolCalendarEntity> schoolCalendarEntity= schoolCalendarDao.findCalenderChooseClass(chooseClass);
        return schoolCalendarEntity;
    }

    /**
     * 查询具体校历事件
     * @param termId
     * @param eventId
     * @return
     */

    @Override
    public SchoolCalendarEntity findCalendarEvent(String termId, String eventId) {

        Map<String,String> eventIdMap = new HashMap<>();
        eventIdMap.put("考试周","0");
        eventIdMap.put("教学周","1");
        eventIdMap.put("选课周","2");
        eventIdMap.put("评教周","3");
        eventIdMap.put("体测周","4");
        eventIdMap.put("节假日","5");
        eventIdMap.put("军训周","6");
        eventIdMap.put("体检周","7");
        eventIdMap.put("新生报到周","8");
        eventIdMap.put("运动会","9");
        eventId = (eventIdMap.get(eventId));
        SchoolCalendarEntity schoolCalendarEntity= schoolCalendarDao.findCalendarEvent(termId,eventId);
        return schoolCalendarEntity;
    }

    @Override
    public PageInfo<SchoolCalendarModel> queryCalendarByRoleIdListAndGradList(String termId, String  roleId, String schoolYear, Integer pageNo, Integer pageSize) {
        termId=termId.trim();
        roleId=roleId.trim();
        schoolYear=schoolYear.trim();
        PageHelper.startPage(pageNo, pageSize);
        List<SchoolCalendarModel> schoolCalendarModelList = schoolCalendarDao.queryCalendarByRoleIdListAndGradList(termId, roleId, schoolYear, pageNo, pageSize);

        return new PageInfo<>(schoolCalendarModelList);
    }
}
